package com.cloudkinto.controller.user;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.user.UserService;
import com.cloudkinto.service.user.vo.*;
import com.cloudkinto.session.UserSession;
import com.cloudkinto.session.UserSessionManager;
import com.cloudkinto.utils.WxCheckoutUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-05-27
 */
@RestController
@Api(tags = "用户模块")
@RequestMapping("/api/user")
public class UserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService service;
    @Autowired
    private UserSessionManager userSessionManager;

    @PostMapping("test")
    @ApiOperation(value = "测试", notes = "测试")
    public SingleResult test() {
        service.test();
        return SingleResult.success("登录成功");
    }

    @PostMapping("login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public SingleResult login(@RequestBody @Validated UserLoginReq req,HttpServletRequest request) {
        return SingleResult.success("登录成功", service.login(req,request));
    }

    @UserSessionRequired
    @PostMapping("main")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public SingleResult main(HttpServletRequest request) {
        return SingleResult.success("登录成功", service.main(request.getHeader("token"),request.getHeader("lang")));
    }


    @UserSessionRequired
    @PostMapping("logout")
    @ApiOperation(value = "用户退出登录", notes = "用户退出登录")
    public SingleResult logout(@RequestHeader String token) {
        service.logout(token);
        return SingleResult.success("退出成功", null);
    }

    @PostMapping("register")
    @ApiOperation(value = "用户注册", notes = "Stoc用户注册")
    public SingleResult register(@RequestBody @Validated UserRegisterReq req) {
        return SingleResult.success("注册成功", service.register(req));
    }

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.addInit(companyId);
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated UserBuildReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId, companyId));
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改个人信息", notes = "修改")
    public SingleResult update(@RequestBody @Validated UserUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @PutMapping("updatePassword")
    @ApiOperation(value = "修改密码", notes = "修改")
    public SingleResult updatePassword(@RequestBody @Validated UpdatePasswordReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.updatePassword(req, userId));
    }

    @UserSessionRequired
    @PostMapping("bindKey")
    @ApiOperation(value = "绑定公钥", notes = "绑定")
    public SingleResult bindKey(@RequestBody @Validated UserBindReq req) {
        Long userId = getCurrentUserId();
        return service.bindKey(req, userId);
    }
   /* @ApiOperation("授权商店")
    @GetMapping("/authorizeShop")
    public SingleResult<GetAuthorizedShopsResponse> authorizeShop(String shopId) throws Exception {
        return SingleResult.success(service.authorizeShop(shopId));
    }*/
    @ApiOperation("tiktok回调函数")
    @GetMapping("/callback")
    public SingleResult<AuthResponse> handleCallback( String code) throws Exception {
        return service.getAccessToken(code);
    }


    @UserSessionRequired
    @PostMapping("/authorization/amazon")
    @ApiOperation(value = "绑定Amaozn公钥", notes = "绑定")
    public SingleResult authorizationAmazon(@RequestBody @Validated Map<String, String> req) {
        Long userId = getCurrentUserId();
        return service.getAuthorizeMsg(getShopId(), req, userId);
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "roleId", value = "角色"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String roleId = request.getParameter("roleId");

        map.put("companyId", String.valueOf(companyId));
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        map.put("roleId", roleId);

        return service.getListPage(map);
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id);
    }

    @UserSessionRequired
    @GetMapping("/bindKey/init")
    @ApiOperation(value = "获取平台初始化", notes = "新增初始化")
    public SingleResult bindKey() {
        return service.bindKeyInit();
    }

    @GetMapping("/authorization/shopify")
    @ApiOperation(value = "shopify认证授权", notes = "shopify认证授权")
    public SingleResult shopifyGetAuthorization(@RequestHeader("token") String token, Long shopId, String code, String session, String state, String host, String hmac, String shop, String timestamp) {
        UserSession userSession = userSessionManager.getSession(token);
        if (userSession == null) userSession = new UserSession();
        return service.shopifyGetAuthorization(shopId != null ? shopId : userSession.getShopId(), userSession.getCompanyId(),
                code, session, state, host, hmac, shop, timestamp);
    }

    @UserSessionRequired
    @PostMapping("/bindKey/yahoo/getUrl")
    @ApiOperation(value = "获取Yahoo授权", notes = "获取Yahoo授权")
    public SingleResult getUrl(@RequestBody @Validated YahooAuthReq req) {
        return SingleResult.success(service.getYahooAuthorizeUrl(req, getCurrentUserId()));
    }

    @UserSessionRequired
    @GetMapping("/bindKey/yahoo/getTokenByCode")
    @ApiOperation(value = "Yahoo获取刷新令牌", notes = "Yahoo获取刷新令牌")
    public SingleResult getTokenByCode(Long shopId, String state, String code) {
        Long companyId = getCompanyId();
        return SingleResult.success("参数已收到", service.getYahooRefreshTokenByCode(shopId, code, state));
//        return SingleResult.success("授权成功", service.getYahooRefreshTokenByCode(shopId, code, state));
    }

    @UserSessionRequired
    @GetMapping("/bindKey/yahoo/getUserInfo")
    @ApiOperation(value = "根据店铺获取店铺信息", notes = "根据店铺获取店铺信息")
    public SingleResult getYahooUserInfo(@RequestParam @Validated @NotBlank(message = "pls.choose.shop")Long shopId) {
        Long companyId = getCompanyId();
        return SingleResult.success(service.getYahooUserInfoApi(shopId));
    }

    @UserSessionRequired
    @GetMapping("/bindKey/init/shopListFromPlantForm")
    @ApiOperation(value = "根据平台获取店铺", notes = "根据平台获取店铺")
    public SingleResult
    shopListFromPlantForm(Long plantFormId) {
        Long companyId = getCompanyId();
        return service.shopListFromPlantForm(plantFormId, companyId);
    }

    @UserSessionRequired
    @GetMapping("/bindKey/keySecret")
    @ApiOperation(value = "获取秘钥", notes = "新增初始化")
    public SingleResult keySecret(@RequestParam Long plantFormId, @RequestParam Long shopId) {
        return service.keySecret(plantFormId, shopId);
    }

    @GetMapping("verificationCode")
    @ApiOperation(value = "获取验证码", notes = "")
    public SingleResult verificationCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return service.verificationCode();
    }

    @GetMapping("getPhoneByAccount")
    @ApiOperation(value = "根据账号获取手机号邮箱号", notes = "")
    public SingleResult getPhoneByAccount(@RequestParam @Validated @NotBlank(message = "pls.input.account.info") String userAccount) throws IOException {
        return service.getPhoneByAccount(userAccount);
    }

    @PostMapping("verificationCodeByPhone")
    @ApiOperation(value = "获取验证码", notes = "")
    public SingleResult verificationCodeByPhone(@RequestBody @Validated SendMsgReq req) throws IOException {
        return service.verificationCodeByPhone(req);
    }

    @PostMapping("verificationCodeCheck")
    @ApiOperation(value = "验证码校验", notes = "")
    public SingleResult verificationCodeByPhone(@RequestBody @Validated CheckCodeReq req) throws IOException {
        return service.verificationCodeCheck(req);
    }

    @PostMapping("findBackPassword")
    @ApiOperation(value = "找回密码", notes = "")
    public SingleResult verificationCodeByPhone(@RequestBody @Validated FindBackPasswordReq req) throws IOException {
        return service.findBackPassword(req);
    }







    @UserSessionRequired
    @GetMapping("/getOmsBindingInfo")
    @ApiOperation(value = "获取OMS绑定信息", notes = "获取OMS绑定信息")
    public SingleResult getOmsBindingInfo() {
        Long userId = getCurrentUserId();
        return service.getOmsBindingInfo(userId);
    }

    @UserSessionRequired
    @PostMapping("/setOmsBindingInfo")
    @ApiOperation(value = "保存OMS绑定信息", notes = "保存OMS绑定信息")
    public SingleResult setOmsBindingInfo(@RequestBody UserUpdateOmsReq req) {
        Long userId = getCurrentUserId();
        return service.setOmsBindingInfo(req, userId);
    }



    /********************绑定公众号功能块*******************/
    @UserSessionRequired
    @PostMapping("getBindingTicket")
    @ApiOperation(value = "①获取绑定二维码", notes = "①获取绑定二维码")
    public SingleResult getBindingTicket() {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.createTicket(userId));
    }

    @PostMapping("scanningCode")
    @ApiOperation(value = "②扫码后获取微信数据包", notes = "②扫码后获取微信数据包")
    public String scanningCode(@RequestBody String request) {
        return service.scanningCode(request);
    }

    @GetMapping("scanningCode")
    @ApiOperation(value = "微信数据验证", notes = "")
    public void scanningCodeGet(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名
        String signature = request.getParameter("signature");
        System.out.println(signature);
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        System.out.println(timestamp);
        // 随机数
        String nonce = request.getParameter("nonce");
        System.out.println(nonce);
        // 随机字符串
        String echostr = request.getParameter("echostr");
        System.out.println(echostr);
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (signature != null && WxCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
            try {
                PrintWriter print = response.getWriter();
                print.print(echostr);
//                print.flush();
                System.out.println("true");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @PostMapping("whetherBindingScan")
    @ApiOperation(value = "③【绑定】二维码是否扫描", notes = "③【绑定】二维码是否扫描")
    public SingleResult whetherBindingScan(@RequestBody ScanningCodeRes req) {
        return service.whetherBindingScan(req);
    }
}

